// RequestJs.js
// JiraClient.js
// JiraMapping.js
// TicketStatusMapping.js
class TicketStatus
{
    constructor(options)
    {
        if (Object.keys(options.source).length &&
            Object.keys(options.target).length
        ) {
            if (options.source.url && !options.source.host) {
                options.source.host = options.source.url;
            }
            if (options.target.url && !options.target.host) {
                options.target.host = options.target.url;
            }
            this.sourceJira = new JiraClient(options.source);
            this.targetJira = new JiraClient(options.target);
            this.mapping = new TicketStatusMapping();
        }
    }

    async getRelatedIssues(issueKeys)
    {
        let self = this;
        let jql = 'key in(' + issueKeys + ')';
        return await self.targetJira.search(jql, {size:200});
    }

    getIssueKeys()
    {
        let issueList = [];
        jQuery('.customfield_10700').each((idx, col) => {
            let key = jQuery(col).text().trim();
            // jQuery(col).attr('id', key);
            if (key && key !="fixVersion 是必须得") {
                jQuery(col).parent().attr('id', key);
                issueList.push(key);
            } else {
                jQuery(col).css({"background-color":"red"}).html("fixVersion 是必须得");
            }
        });
        console.log('##list', issueList);
        return issueList;
    }

    async validateStatus()
    {
        let self = this;
        let issueKeys = self.getIssueKeys();

        if (issueKeys.length) {
            let respPromise = await self.getRelatedIssues(issueKeys.join(',')).then(resp => resp.json())
                .then(resp => {
                    if (resp.total) {
                        resp.issues.forEach(_issue => {
                           let issue = self.mapping.convert(_issue);
                            console.log('##issue', issue);
                           self.renderResult(issue);
                        });
                    }
                    jQuery('#sync-loading').remove();
                });
        }
    }

    renderResult(issue)
    {
        // fix version issue
        let $fixVersion = jQuery('#' + issue.fields.key + ' .fixVersions a');
        let equalFixVersion = $fixVersion.text() == issue.fields.fixVersion;
        if (!equalFixVersion) {
            $fixVersion.css({"color":"#FFCC33"});
        }

        // customfield_10202 CheckList
        var html = '';
        Object.keys(issue.fields).forEach((field) => {
            if (field=='key') {
                html += '<li>' + field + '：<span class="tkey" style="cursor: pointer;color: blue;">' + issue.fields[field] +  '<span></li>';
            } else if(field=='fixVersion' && !equalFixVersion) {
                html += '<li>' + field + '：<span style="color:#FFCC33;">' + issue.fields[field] +  '</span></li>';
            } else {
                html += '<li>' + field + '：' + issue.fields[field] +  '</li>';
            }
        });
        html = '<ol>' + html + '</ol>';
        jQuery('#' + issue.fields.key + ' .customfield_10202').html(html);
        jQuery('.tkey').on('click', function(e){
            let tHost = JSON.parse(localStorage.getItem('config')).target.host;
            window.open(tHost + '/browse/' + jQuery(this).text(), '_blank');
            alert(tHost + '/browse/' + jQueyr(this).text());
        });
    }

    init()
    {
        let self = this;
        jQuery('.saved-search-operations').append('<button id="comparison">Comparison</button>');
        jQuery('#comparison').on('click', (e) => {
            // validate required field
            if (jQuery('.customfield_10700').length<1 || jQuery('.customfield_10202').length <1) {
                alert("Fix Version/s 和 Checklists 列是必须的");
            } else {
                jQuery('#sync-loading').remove();
                jQuery('.saved-search-operations').append('<div id="sync-loading" class="lds-dual-ring"></div>');
                jQuery('.customfield_10202').html('');
                try {
                    self.validateStatus();
                } catch (e) {
                    alert(e);
                }
            }
        });
    }
}
var ticketStatus = new TicketStatus(JSON.parse(localStorage.getItem('config')));
ticketStatus.init();